﻿using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.IO;

public class UnityEditorTools
{
    [MenuItem("Tools/RelaceShader")]
    public static void RelaceShader()
    {
        RelaceShaderWindow myWindow = (RelaceShaderWindow)EditorWindow.GetWindow(typeof(RelaceShaderWindow), false, "RelaceShader", true);//创建窗口

        myWindow.Show();//展示
    }
    public class RelaceShaderWindow:EditorWindow
    {
        private string oldShaderName;
        private string newShaderName;
        private void OnGUI()
        {
            EditorGUILayout.LabelField("要替换的Shader");
            oldShaderName= EditorGUILayout.TextField(oldShaderName);
            EditorGUILayout.LabelField("替换成的Shader");
            newShaderName = EditorGUILayout.TextField(newShaderName);
            if (GUILayout.Button("替换"))
            {
                if (string.IsNullOrEmpty(oldShaderName) || string.IsNullOrEmpty(newShaderName))
                {
                    Debug.LogError("Shader名为空");
                    return;
                }
                Shader shader = Shader.Find(newShaderName);
                string[] tempMaterialsPath = AssetDatabase.GetAllAssetPaths();
                List<Material> tempMaterials = new List<Material>();
                for (int i = 0; i < tempMaterialsPath.Length; i++)
                {
                    string ext = Path.GetExtension(tempMaterialsPath[i]);
                    if (ext != ".mat")
                    {
                        continue;
                    }
                    tempMaterials.Add(AssetDatabase.LoadAssetAtPath(tempMaterialsPath[i], typeof(Material)) as Material);
                }
                if (tempMaterials.Count != 0)
                {
                    for (int i = 0; i < tempMaterials.Count; i++)
                    {
                        if (tempMaterials[i] == null)
                        {
                            continue;
                        }
                        if (tempMaterials[i].shader.name == oldShaderName)
                        {
                            tempMaterials[i].shader = shader;
                        }
                    }
                }
            }
        }
    }
}
